package gu.simplemq.proton;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.jms.Connection;
import javax.jms.ExceptionListener;
import javax.jms.JMSException;
import org.apache.activemq.jms.pool.ConnectionPool;
import org.apache.qpid.jms.JmsConnection;
import org.apache.qpid.jms.JmsConnectionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import gu.simplemq.utils.IntrospectionSupport;

/**
 * copy from org.apache.activemq.pool.PooledConnectionFactory
 * Add Service and Referenceable and TransportListener to @link{org.apache.activemq.jms.pool.PooledConnectionFactory}
 *
 */
public class PooledConnectionFactory extends org.apache.activemq.jms.pool.PooledConnectionFactory   {
    public static final String POOL_PROPS_PREFIX = "pool";

    private static final transient Logger LOG = LoggerFactory.getLogger(org.apache.activemq.jms.pool.PooledConnectionFactory.class);

    public PooledConnectionFactory() {
        super();
    }

    public PooledConnectionFactory(JmsConnectionFactory jmsConnectionFactory) {
        setConnectionFactory(jmsConnectionFactory);
    }

    public PooledConnectionFactory(String brokerURL) {
        setConnectionFactory(new JmsConnectionFactory(brokerURL));
    }

    @SuppressWarnings({ "unchecked", "rawtypes" })
    protected void buildFromProperties(Properties props) {
    	JmsConnectionFactory jmsConnectionFactory = new JmsConnectionFactory();
        jmsConnectionFactory.setProperties((Map)props);
        setConnectionFactory(jmsConnectionFactory);
        IntrospectionSupport.setProperties(this, new HashMap(props), POOL_PROPS_PREFIX);
    }

    @Override
    protected void populateProperties(Properties props) {
        Map<String, String> result = ((JmsConnectionFactory)getConnectionFactory()).getProperties();
        props.putAll(result);
        super.populateProperties(props);
    }

    public void setProperties(Properties properties) {
        buildFromProperties(properties);
    }

    public Properties getProperties() {
        Properties properties = new Properties();
        populateProperties(properties);
        return properties;
    }

    @Override
    protected Connection newPooledConnection(ConnectionPool connection) {
        return new org.apache.activemq.jms.pool.PooledConnection(connection);
    }

    @Override
    protected org.apache.activemq.jms.pool.ConnectionPool createConnectionPool(Connection connection) {
        return new ConnectionPool(connection) {

            @Override
            protected Connection wrap(final Connection connection) {
                // Add a transport Listener so that we can notice if this connection
                // should be expired due to a connection failure.
                try {
					((JmsConnection)connection).setExceptionListener(new ExceptionListener() {

					    @Override
					    public void onException(JMSException error) {
					        synchronized (this) {
					            setHasExpired(true);
					            // only log if not stopped
					            if (!stopped.get()) {
					                LOG.info("Expiring connection " + connection + " on IOException: " + error.getMessage());
					                // log stacktrace at debug level
					                LOG.debug("Expiring connection " + connection + " on IOException: ", error);
					            }
					        }
					    }

					});
				} catch (JMSException e) {
					e.printStackTrace();
				}

                // make sure that we set the hasFailed flag, in case the transport already failed
                // prior to the addition of our new TransportListener
                setHasExpired(((JmsConnection)connection).isFailed());

                // may want to return an amq EnhancedConnection
                return connection;
            }

            @Override
            protected void unWrap(Connection connection) {
                if (connection != null) {
                	IntrospectionSupport.getProperty((JmsConnection)connection, "tempDestinations", Map.class).clear();
                }
            }
        };
    }    

}
